package com.eascs.ticket.schedule.scheduler;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.template.TemplateHelper;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.ticket.configuration.entity.TicketTypeConstant;
import com.eascs.ticket.configuration.service.WorkdayService;
import com.eascs.ticket.schedule.entity.ScheduleTicket;
import com.eascs.ticket.schedule.entity.ScheduleTicketOperator;
import com.eascs.ticket.schedule.service.ScheduleTicketOperatorService;
import com.eascs.ticket.schedule.service.ScheduleTicketService;
import com.eascs.ticket.ticket.controller.InsertTicketComponet;
import com.eascs.ticket.ticket.entity.Ticket;
import com.eascs.ticket.ticket.form.InsertTicketForm;
import com.eascs.ticket.ticket.service.TicketService;
import com.eascs.ticket.ticket.vo.TicketUpdateOperatorVo;
import com.eascs.ticket.user.component.SystemUserHolder;
import com.eascs.ticket.user.entity.User;
import com.eascs.ticket.user.service.UserService;

@Component
public class ScheduleTicketScheduler {
	private static Logger logger = LoggerFactory.getLogger(ScheduleTicketScheduler.class);

	@Inject
	private ScheduleTicketOperatorService scheduleTicketOperatorService;

	@Inject
	private ScheduleTicketService scheduleTicketService;

	@Inject
	private InsertTicketComponet insertTicketComponet;

	@Inject
	private UserService userService;

	@Inject
	private SystemUserHolder systemUserHolder;

	@Inject
	private TicketService ticketService;

	@Inject
	private WorkdayService workdayService;

	@Scheduled(cron = "0 0 3 * * ?")
	public void buildTickect() {
		logger.info("start ScheduleTicketScheduler.buildTickect");
		this.systemUserHolder.holde();
		List<ScheduleTicket> scheduleTickets = scheduleTicketService.getValidScheduleTicketList();
		String weekOfDate = String.valueOf(DateUtils.getWeekOfDate(new Date()));
		logger.info("weekOfDate={} ", weekOfDate);
		logger.info("scheduleTicketService.getValidScheduleTicketList scheduleTickets size={} ", scheduleTickets.size());
		for (ScheduleTicket scheduleTicket : scheduleTickets) {
			logger.info("scheduleTicket={} ", scheduleTicket.toString());
			List<ScheduleTicketOperator> scheduleTicketOperators = scheduleTicketOperatorService.getScheduleTicketOperatorListByScheduleTicketId(scheduleTicket.getId());
			logger.info("scheduleTicketOperatorService.getScheduleTicketOperatorListByScheduleTicketId ScheduleTicketId={},scheduleTicketOperators size=", scheduleTicket.getId(), scheduleTicketOperators.size());
			if (scheduleTicketOperators.isEmpty() || StringUtil.isEmpty(scheduleTicket.getWeekday())) {
				continue;
			}
			if (scheduleTicket.getWeekday().indexOf(weekOfDate) < 0) {
				continue;
			}
			for (ScheduleTicketOperator scheduleTicketOperator : scheduleTicketOperators) {
				buildTickect(scheduleTicket, scheduleTicketOperator);
			}
		}
		this.systemUserHolder.rest();
	}

	private void buildTickect(ScheduleTicket scheduleTicket, ScheduleTicketOperator scheduleTicketOperator) {
		java.sql.Date currentDate = new java.sql.Date(DateUtils.truncateTime(new Date()).getTime());

		if (!this.workdayService.isWorkDay(currentDate)) {
			// 非工作日
			if (null != scheduleTicket.getWeekday() && scheduleTicket.getWeekday().indexOf("2,3,4,5,6") >= 0) {
				// 每天创建的单可以不需要创建
				return;
			} else {
				// 计算下个工作日
				currentDate = new java.sql.Date(this.workdayService.getNextWorkDay(currentDate).getTime());
			}

		}
		// 根据工作日算法得到下个工作日为复核日
		java.sql.Date implementationReviewTime = new java.sql.Date(workdayService.getNextWorkDay(currentDate, scheduleTicket.getDays()).getTime());

		InsertTicketForm insertTicketForm = new InsertTicketForm();
		Map<String, Object> templateData = new HashMap<>();
		insertTicketForm.setImplementationReviewTime(implementationReviewTime);
		User user = userService.getUserByCode(scheduleTicketOperator.getOperator());

		templateData.put("implementationReviewTime", implementationReviewTime);
		templateData.put("currentDate", currentDate);
		templateData.put("user", user);

		insertTicketForm.setProjectId("auto");
		insertTicketForm.setTicketTypeCode(scheduleTicket.getTicketType());
		insertTicketForm.setModuleId(scheduleTicket.getModuleId());
		insertTicketForm.setPriority("general");
		insertTicketForm.setTitle(buildStringFromStringTemplate(scheduleTicket.getTitle(), templateData));
		insertTicketForm.setDescriptions(buildStringFromStringTemplate(scheduleTicket.getDescription(), templateData));

		if (TicketTypeConstant.TICKET_TYPE_CODE_TASK.equals(scheduleTicket.getTicketType()) || TicketTypeConstant.TICKET_TYPE_CODE_WORKLOG.equals(scheduleTicket.getTicketType())) {
			insertTicketForm.setQaValidatedTime(new java.sql.Date(workdayService.getNextWorkDay(implementationReviewTime, 1).getTime()));
		}

		Ticket ticket = insertTicketComponet.insertTicket(insertTicketForm);
		logger.info("create ticket id={}", ticket.getId());

		TicketUpdateOperatorVo ticketUpdateOperatorVo = new TicketUpdateOperatorVo();
		ticketUpdateOperatorVo.setTicketId(ticket.getId());
		ticketUpdateOperatorVo.setComments("自动分配");
		ticketUpdateOperatorVo.setOperator(scheduleTicketOperator.getOperator());
		this.ticketService.updateTicketOperator(ticketUpdateOperatorVo);
		logger.info("assign ticket id={} to Operator={}", ticket.getId(), scheduleTicketOperator.getOperator());
	}

	private String buildStringFromStringTemplate(String stringTemplate, Map<String, Object> data) {
		return TemplateHelper.processStringTemplate(stringTemplate, data);
	}

}
